package com.glory.wxmemsicpda.activity

import android.Manifest
import android.annotation.SuppressLint
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.view.View
import com.glory.wxmemsicpda.R
import com.glory.wxmemsicpda.base.BaseDialogActivity
import com.glory.wxmemsicpda.base.Constant
import com.glory.wxmemsicpda.base.Constant.CURRENT_USER
import com.glory.wxmemsicpda.base.Constant.FILE_URL
import com.glory.wxmemsicpda.bean.LoginBean
import com.glory.wxmemsicpda.bean.net.BaseResponseBean
import com.glory.wxmemsicpda.utils.MyUtils.isFastClick
import com.glory.wxmemsicpda.utils.NetUtils
import com.google.gson.JsonObject
import com.google.gson.reflect.TypeToken
import com.lzy.okgo.model.Response
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_SimpleDialogEntityCallBack
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_DownloadFragmentDialog
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_VersionEntity
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_ActivityManager
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_NetUtils
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_Utils
import kotlinx.android.synthetic.main.activity_login.*
import pub.devrel.easypermissions.AfterPermissionGranted
import pub.devrel.easypermissions.AppSettingsDialog
import pub.devrel.easypermissions.EasyPermissions
import pub.devrel.easypermissions.EasyPermissions.PermissionCallbacks
import java.util.*

class LoginActivity : BaseDialogActivity(), PermissionCallbacks, View.OnClickListener {
    override fun getLayoutResId(): Int {
        return R.layout.activity_login
    }

    override fun initView() {
//        String userName = FreeApi_SharePreferencesUtils.getSharePre("URL_FILE", "USERNAME", "", App.app);
//        String passWord = FreeApi_SharePreferencesUtils.getSharePre("URL_FILE", "PASSWORD", "", App.app);
//        etMobile.setText(userName);
//        etPassword.setText(passWord);
        requestPermission()
        btnLogin.setOnClickListener(this)
        ivSetting.setOnClickListener(this)
    }

    @SuppressLint("SetTextI18n")
    override fun initData() {
        tvVersion.text = "V" + FreeApi_Utils.getVerName()
        detectionUpdate()
    }

    override fun getBaseEntity(): FreeUI_AddViewEntity? {
        return null
    }

    private fun detectionUpdate() {
        val manager = packageManager
        var info: PackageInfo? = null
        try {
            info = manager.getPackageInfo(packageName, 0)
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
        }
        val version = info!!.versionName
        val callBack: FreeUI_EntityCallBack<FreeUI_VersionEntity?> = object :
            FreeUI_EntityCallBack<FreeUI_VersionEntity?>(object :
                TypeToken<FreeUI_VersionEntity?>() {}.type) {
            override fun onSuccess(response: Response<FreeUI_VersionEntity?>?) {
                val entity = response!!.body()
                entity!!.currentVersion = version
                val code = FreeApi_Utils.compareVersion(version, entity.version)
                if (code == -1) {
                    val downloadFragmentDialog = FreeUI_DownloadFragmentDialog()
                    downloadFragmentDialog.setData(entity)
                    downloadFragmentDialog.show(supportFragmentManager, "DOWNLOAD")
                }
            }

            override fun onError(response: Response<FreeUI_VersionEntity?>?) {
                super.onError(response)
            }
        }
        val map: Map<String, String> = HashMap()
        FreeApi_NetUtils.requestGetNet(FILE_URL + "/PDA/Version.txt", this, map, callBack)
    }


    @AfterPermissionGranted(PERMISSIONS_REQUEST_CODE)
    private fun requestPermission() {
        val perms = arrayOf(
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
        )
        //权限判断，第一次弹出系统的授权提示框
        if (EasyPermissions.hasPermissions(this, *perms)) {
            //@AfterPermissionGranted 有权限直接执行 todo...
        } else {
            //没有权限的话，先提示，点确定后弹出系统的授权提示框
            EasyPermissions.requestPermissions(
                this, "程序运行需要权限",
                PERMISSIONS_REQUEST_CODE, *perms
            )
        }
    }

    private fun login() {
//        var ss = "{\"Response\":{\"Header\":{\"TRANSACTIONID\":\"c5e5e318389d4c39b914e4c10ba519d4\",\"RESULT\":\"SUCCESS\"},\"Body\":{\"LOGINRESULT\":true,\"USER\":{\"ORGNAME\":\"SBE\",\"USERNAME\":\"admin\",\"DESCRIPTION\":\"超级管理员\",\"DEFAULTLANGUAGE\":\"EN\",\"DEFAULTORGRRN\":378341,\"ISCLIENTENCRY\":\"N\",\"TOKEN\":\"5HqoYfUedydKhSoJqXnVtr\"}}}}"
//        var dd : BaseResponseBean<LoginBean> = Gson().fromJson(ss,object : TypeToken<BaseResponseBean<LoginBean>>(){}.type)

        val map = JsonObject()
        map.addProperty("ACTIONTYPE", "LOGIN")
        map.addProperty("USERNAME", etMobile!!.text.toString().trim { it <= ' ' })
        map.addProperty("PASSWORD", etPassword!!.text.toString().trim { it <= ' ' })
        NetUtils.requestPosNet(this, "PDALogin","SYS.USER_LOGIN",
            map, object : FreeUI_SimpleDialogEntityCallBack<BaseResponseBean<LoginBean?>?>(this) {
                override fun onSuccess(response: Response<BaseResponseBean<LoginBean?>?>) {
                    super.onSuccess(response)
                    if (response.body()!!
                            .isSuccess(false, supportFragmentManager)
                    ) {
                        CURRENT_USER = etMobile!!.text.toString().trim { it <= ' ' }
                        Constant.CURRENT_PWD = etPassword!!.text.toString().trim { it <= ' ' }
                        Constant.CURRENT_LOGINBEAN = response.body()!!.response.body!!
                        showToast("登陆成功", true)
                        FreeApi_ActivityManager.getActivityManager().finishAllActivity()
                        FreeApi_Utils.skipWithExtraIntent(
                            "",
                            this@LoginActivity,
                            HomeActivity::class.java
                        )
                    }
                }

                override fun onError(response: Response<BaseResponseBean<LoginBean?>?>) {
                    super.onError(response)
                    loadError(response.exception, "PDALogin")
                }

            })
//        FreeApi_ActivityManager.getActivityManager().finishAllActivity();
//        FreeApi_Utils.skipWithExtraIntent("", this@LoginActivity, HomeActivity::class.java)
    }

    /**
     * 允许权限成功后触发
     */
    override fun onPermissionsGranted(requestCode: Int, perms: List<String>) {}

    /**
     * 禁止权限后触发
     */
    override fun onPermissionsDenied(requestCode: Int, perms: List<String>) {
        showToast("用户授权失败", false)
        /**
         * 若是在权限弹窗中，用户勾选了'NEVER ASK AGAIN.'或者'不在提示'，且拒绝权限。
         * 这时候，需要跳转到设置界面去，让用户手动开启。
         */
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            AppSettingsDialog.Builder(this).build().show()
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }

    companion object {
        private const val PERMISSIONS_REQUEST_CODE = 10
    }

    override fun onClick(p0: View?) {
        if (isFastClick) {
            showToast("您点击的太快了", false)
            return
        }
        when (p0?.id) {
            R.id.ivSetting -> FreeApi_Utils.skipWithExtraIntent(
                "header",
                this@LoginActivity,
                SettingActivity::class.java
            )
            R.id.btnLogin -> {
                if (etMobile!!.text.toString().trim { it <= ' ' }.isEmpty()) {
                    showToast("请输入用户名", false)
                    return
                }
                if (etPassword!!.text.toString().trim { it <= ' ' }.isEmpty()) {
                    showToast("请输入密码", false)
                    return
                }

                //region 测试
//                showToast("登陆成功", true)
//                FreeApi_ActivityManager.getActivityManager().finishAllActivity()
//                FreeApi_Utils.skipWithExtraIntent(
//                    "",
//                    this@LoginActivity,
//                    HomeActivity::class.java
//                )
                //endregion

                login()
            }
        }
    }
}